package com.morsth.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ToolsUtils {
    public static Logger  logger  = Logger.getLogger(ToolsUtils.class);

    public static Boolean checkIfWeekEnd(String dateStr){
        //判断日期是否是周末
        DateFormat  dt  = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date  =  dt.parse(dateStr);
            Calendar  calendar  =Calendar.getInstance();
            calendar.setTime(date);
            if(calendar.get(Calendar.DAY_OF_WEEK)  == Calendar.SATURDAY  ||  calendar.get(Calendar.DAY_OF_WEEK)  == Calendar.SUNDAY ){
                return  true;
            }else{
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            logger.info("转换日期失败,传递dataset=" + dateStr);
            return  false;
        }
    }


    public static  boolean checkUuid(String uuid) throws IOException {
        InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
        SqlSession sqlSession = factory.openSession();
        boolean result = false;
         if((int)sqlSession.selectOne("com.morsth.dao.checkUuid",uuid)  > 0 ){
             result = true;
         }else{
             result  = false;
         }
        sqlSession.close();
        return result;
    }

    public static boolean checkDate(String dateStr) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setLenient(false);
        try {
            sdf.parse(dateStr);
        } catch (ParseException e) {
            return  false;
        }

        return   true;
    }

    public  static boolean checkYear(String dateStr) throws IOException {
        InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
        SqlSession sqlSession = factory.openSession();
        boolean result = false;
        if((int)sqlSession.selectOne("com.morsth.dao.checkYearInDB",dateStr)  > 0 ){
            result = true;
        }else{
            result  = false;
        }
        sqlSession.close();
        return result;

    }

}
